<template>
  <div class="container">
    <a-space direction="vertical" size="large">
      <a-input-search
        v-model="inputDomain"
        placeholder="请输入域名"
        :style="{ width: '320px', display: 'flex', flexDirection: 'row' }"
        @search="handleSearch"
      />
    </a-space>
    <a-divider style="margin-top: 16px" />

    <!-- 分析页面 -->
    <AnalysisPage v-if="isAnalyzing" :domain="inputDomain" @progress-complete="onAnalysisComplete" />

    <!-- 结果页面 -->
    <ResultPage
      v-else
      :domainList="domainList"
      :loading="loading"
      :pagination="pagination"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick } from 'vue';
import axios from 'axios';
import AnalysisPage from './analysis.vue';
import ResultPage from './domainresult.vue';

const inputDomain = ref('');
const loading = ref(false);
const domainList = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
const isAnalyzing = ref(false);

// 调用后端 API 进行预测
const fetchData = async (domain: string) => {
  loading.value = true;
  try {
    const requestData = {
      domain: domain
    };
    console.log('Request data:', requestData); // 添加日志
    const response = await axios.post('http://localhost:5000/predict', requestData);
    const result = response.data;
    if (result.error) {
      console.error('后端返回错误:', result.error);
      // 可以在这里添加更多的错误处理逻辑，比如显示错误提示框
      return;
    }
    // 添加预测时间戳
    result.timestamp = new Date().toLocaleString();
    domainList.value = [result];
    pagination.total = 1;
  } catch (err) {
    console.error('Error fetching data:', err);
    // 可以在这里添加更多的错误处理逻辑，比如显示错误提示框
  } finally {
    loading.value = false;
    isAnalyzing.value = false;
    console.log('isAnalyzing updated to:', isAnalyzing.value); // 添加日志确认状态更新
  }
};

const handleSearch = () => {
  if (inputDomain.value) {
    isAnalyzing.value = true;
    console.log('Analysis started. isAnalyzing:', isAnalyzing.value); // 添加日志确认状态更新
  }
  
};

const onAnalysisComplete = async () => {
  if (inputDomain.value) {
    await fetchData(inputDomain.value);
  }
};

// 初始化加载数据
nextTick(() => {
  if (inputDomain.value) {
    isAnalyzing.value = true;
  }
});
</script>

<style scoped lang="less">
.container {
  padding: 20px;
}
</style>